package com.interviews.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 需求变成了 1000 个线程都要用到 SimpleDateFormat
 *
 * @author qian
 * @version 1.0
 * @date 2022/3/3 16:18
 */
public class ThreadLocalDemo03 {


    public static ExecutorService threadPool = new ThreadPoolExecutor(16, 16, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(), new ThreadLocalDemo03ThreadFactory("SimpleDateFormat03"));


    public static void main(String[] args) {

        for (int i = 0; i < 1000; i++) {

            int finalI = i;

            threadPool.submit(() -> {

                String date = new ThreadLocalDemo03().date(finalI);

                System.out.println(date);

            });

        }

        threadPool.shutdown();

    }


    public String date(int seconds) {

        Date date = new Date(1000 * seconds);

        SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");

        return dateFormat.format(date);

    }


    static class ThreadLocalDemo03ThreadFactory implements ThreadFactory {
        private final String namePrefix;
        private final AtomicInteger nextId = new AtomicInteger(1);

        public ThreadLocalDemo03ThreadFactory(String namePrefix) {
            this.namePrefix = "From ThreadLocalDemo03ThreadFactory " + namePrefix + "-Worker-";
        }

        @Override
        public Thread newThread(Runnable r) {
            String name = namePrefix + nextId.getAndIncrement();
            Thread thread = new Thread(null, r, name, 0);
            System.out.println(thread.getName());
            return thread;
        }
    }

}

